import React, { useState, useEffect } from "react";
import { message, Table, Tree, Tag, Spin } from "antd";
import styles from "./index.less";
import {
  get4AChildOrgByParentOrgId,
  get4AUsersByOrgId
} from "../../../../services/acceptGroup";

const { TreeNode } = Tree;

const UsersSelect = props => {
  const {
    usersOfSelected: listOfSelectedUsers,
    setusersOfSelected: setlistOfSelectedUsers
  } = props;
  const [listOfUsers, setlistOfUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [spinLoading, setspinLoading] = useState(true);
  const [orgTreeData, setorgTreeData] = useState([]);

  useEffect(() => {
    getOrgTree();
    return () => {};
  }, []);

  function getOrgTree() {
    get4AChildOrgByParentOrgId().then(res => {
      setorgTreeData(
        res.datas.map(d => ({ ...d, title: d.orgName, key: d.orgId }))
      );
      setspinLoading(false);
    });
  }
  /* eslint no-param-reassign: ["error", { "props": false }] */
  const onLoadData = treeNode =>
    new Promise(resolve => {
      if (treeNode.props.children && treeNode.props.children.length > 0) {
        resolve();
        return;
      }
      get4AChildOrgByParentOrgId({ parentOrgId: treeNode.props.eventKey }).then(
        res => {
          const { datas, errCode, errMsg } = res;
          if (errCode === 0) {
            treeNode.props.dataRef.children = datas.map(d => ({
              ...d,
              key: d.orgId,
              title: d.orgName
            }));
            setorgTreeData([...orgTreeData]);
          } else {
            message.error(errMsg);
          }
          resolve();
        }
      );
    });
  // 树节点选中项变更事件 key:resourceId
  function onOrgTreeSelect(key, { selected }) {
    if (!selected) {
      setlistOfUsers([]);
      return;
    }
    setLoading(true);
    // 获取组织对应岗位用于展示、
    get4AUsersByOrgId({ orgId: key }).then(res => {
      const { datas, errCode, errMsg } = res;
      if (errCode === 0) {
        setlistOfUsers(datas);
      } else {
        message.error(errMsg);
      }
      setLoading(false);
    });
  }
  // 已选中组织删除事件
  const onTagDel = key => {
    // 更新tag列表
    setlistOfSelectedUsers(listOfSelectedUsers.filter(o => o.userId !== key));
  };
  // 渲染树子节点
  const renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} {...item} dataRef={item} />;
    });

  // const onTableChange = pagination => {
  //   setLoading(true);
  //   // 获取组织对应岗位用于展示、
  //   get4AUsersByOrgId({
  //     orgId,
  //     pageSize: pagination.pageSize,
  //     pageNum: pagination.current
  //   }).then(res => {
  //     const { datas, errCode, errMsg } = res;
  //     if (errCode === 0) {
  //       setlistOfUsers(datas);
  //     } else {
  //       message.error(errMsg);
  //     }
  //     setLoading(false);
  //   });
  // };

  // 子组织表格column
  const orgColumn = [
    { dataIndex: "orgId", title: "组织ID" },
    { dataIndex: "orgName", title: "组织名称" },
    { dataIndex: "userId", title: "用户ID" },
    { dataIndex: "userName", title: "用户姓名" },
    { dataIndex: "staff", title: "用户工号" }
  ];
  const rowSelection = {
    selectedRowKeys: listOfSelectedUsers.map(o => +o.userId),
    onSelect: (record, selected) => {
      if (selected) {
        setlistOfSelectedUsers(listOfSelectedUsers.concat([record]));
      } else {
        setlistOfSelectedUsers(
          listOfSelectedUsers.filter(o => +o.userId !== record.userId)
        );
      }
    }
  };
  return (
    <div className={styles.root}>
      <Spin spinning={spinLoading}>
        <div className={styles.section}>
          <div
            style={{
              width: 230,
              display: "flex",
              flexFlow: "column"
            }}
          >
            <div>组织信息</div>
            <Tree
              loadData={onLoadData}
              onSelect={onOrgTreeSelect}
              className={styles.orgTree}
            >
              {renderTreeNodes(orgTreeData)}
            </Tree>
          </div>
          <div style={{ flex: 1 }}>
            <div>组织用户信息</div>
            <div className={styles.menuTable}>
              <Table
                rowKey="userId"
                columns={orgColumn}
                dataSource={listOfUsers}
                rowSelection={rowSelection}
                // onChange={onTableChange}
                pagination={{
                  pageSize: 5
                }}
                loading={loading}
              />
            </div>
          </div>
        </div>
      </Spin>
      <div style={{ padding: "16px 0px" }}>已选：</div>
      <div className={styles.selectedBox}>
        {listOfSelectedUsers.map(rec => (
          <Tag
            style={{ marginBottom: 5 }}
            key={rec.userId}
            closable
            onClose={() => onTagDel(rec.userId)}
          >
            （{rec.userId}）{rec.userName}
          </Tag>
        ))}
      </div>
    </div>
  );
};

export default UsersSelect;
